package com.haiheng.module_main.mode

import android.util.ArrayMap
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.haiheng.common.api.API
import com.haiheng.common.constant.AppConstant
import com.haiheng.library.log.LogWriter
import com.haiheng.library_base.http.Domain
import com.haiheng.library_base.http.HttpRequest
import com.haiheng.library_base.http.get
import com.haiheng.library_base.model.BaseViewModel
import com.haiheng.library_base.model.SingleLiveEvent
import com.haiheng.library_base.utils.SPUtils
import com.haiheng.module_main.bean.res.QueryBookAcsRes
import com.haiheng.module_main.bean.res.bookcar.BookCarBookListRes
import com.haiheng.module_main.bean.res.bookcar.BookCarInfoRes
import kotlinx.coroutines.launch

/**
 *
 * @Des:
 * @Author: hwz
 * @Date:2024/8/20 0020
 * @Version: 1.0
 */
class BookCarInfoViewModel : BaseViewModel() {
    // 使用MutableLiveData<List<Pair<String, String>>>来存储书车信息的键值对列表
    var _bookCarInfoList = SingleLiveEvent<List<Pair<String, String>>>()
    var _failMsg = SingleLiveEvent<String>()
    var _isGetBookNum = SingleLiveEvent<Boolean>()

    // 提供一个不可变的LiveData给观察者
    val bookCarInfoList: LiveData<List<Pair<String, String>>> = _bookCarInfoList
    val failMsg: LiveData<String> = _failMsg
    val isGetBookNum: LiveData<Boolean> = _isGetBookNum


    fun queryBookCarDetail(carNum: String) {
        viewModelScope.launch {
            try {
                val request = HttpRequest(API.BOOK_CAR_PATH.QUARY_MACHINELUID_WANGGUAN)
                    .putHeader(Domain.KEY_NAME, Domain.VALUE_DEFUlT)
                    .putHeader(API.PARAM.PARAM_HEADER_TOKEN,AppConstant.getToken())
                    .putPath("MachineUuid",carNum)
                var response = get<BookCarInfoRes>(request) {}
                if (response.errorCode.equals("0") && response.result != null){
                    // 构建书车信息的键值对列表
                    val list = mutableListOf<Pair<String, String>>()
                    list.add("编号：" to response.result.machineUuid)
                    list.add("书车名：" to response.result.name)
//                    list.add("馆方：" to response.result.libraryCode.toString())
//                    list.add("批次：" to "01")
                    list.add("图书数量：" to "0本")
                    list.add("书车状态：" to "正常")
                    SPUtils.getInstance().put(AppConstant.SP_BOOK_CAR_UUID,response.result.machineUuid)
                    SPUtils.getInstance().put(AppConstant.SP_BOOK_CAR_NAME,response.result.name)
                    // 更新LiveData
                    _isGetBookNum.postValue(true)
                    _bookCarInfoList.postValue(list)
                }else{
                    _failMsg.postValue("${response.message}")
                }

            } catch (ex: Exception) {
                _failMsg.postValue("${ex.message}")
                LogWriter.d("查询书车异常：${ex.message}")
            }
        }
    }

    fun updateBookCount(newBookCount: Int) {
        viewModelScope.launch {
            // 假设你已经有了当前的列表，或者从某个地方获取到了它
            // 这里为了演示，我假设直接从 _bookCarInfoList.value 获取（但注意，这可能需要处理null的情况）
            val currentList = _bookCarInfoList.value ?: emptyList()

            // 创建一个新的列表来存储更新后的数据
            val updatedList = currentList.map { pair ->
                if (pair.first == "图书数量：") {
                    // 如果找到图书数量的项，则更新它
//                    pair.first to "图书数量："
                    pair.first to "${newBookCount}本"
                } else {
                    // 否则，保留原样
                    pair
                }
            }.toMutableList()

            // 将更新后的列表设置为新的值
//            _bookCarInfoList.value = updatedList
            _bookCarInfoList.postValue(updatedList)
        }
    }
}